import { useEffect, useRef, useState } from 'react'
import Taro, { FC, useRouter } from "@tarojs/taro"
import { firstValueFrom, Subscription } from 'rxjs'
import { View, Text, Image, ScrollView } from "@tarojs/components"
import { getLogger } from '@/utils/log'
import { useAuthFacade } from '@/hooks/useAuthFacade'
import { AnchorlatestRsp, GetOrgDetailsRsp, LiveParams } from '@/models/response/userRsp'
import { formatTimes, numFormat } from '@/utils'
import { TMPID_NOW, TMPID_READY } from '@/constants/user'
import qCloudApi from "@/api/qCloudApi";
import CONFIG from "@/config";
import './index.scss'

//机构信息
export const OrgInformation: FC = () => {
  const logger = getLogger("/pages/my/orgInformation");
  const router = useRouter();
  const [authFacade, loginStatus, userId, , , userInfo] = useAuthFacade();
  const [liveOrgList, setLiveOrgList] = useState([] as AnchorlatestRsp[])
  const [orgDetails, setOrgDetails] = useState({} as GetOrgDetailsRsp)
  const [startedList, setStartedList] = useState([] as LiveParams[]) //直播中的数据
  const [noStartedList, setNoStartedList] = useState([] as LiveParams[]) //直播未开始的数据
  const [endedList, setEndedList] = useState([] as LiveParams[]) //直播已结束的数据
  const [navBarHeight, setNavBarHeight] = useState(0);//导航栏高度
  const [navHeight, setNavHeight] = useState(0);//胶囊高度
  const [topPadding, setTopPadding] = useState(0);//胶囊上边距
  const [navWidth, setNavWidth] = useState(0);//胶囊宽度 
  const [statusBarHeight, setstatusBarHeight] = useState(0);//状态栏高度 
  const [screenWidth, setScreenWidth] = useState(0);//屏幕宽度
  const [topMargin, setTopMargin] = useState(0);//高度差 
  const [isAttention, setIsAttention] = useState(router.params.isFollowed as unknown as boolean)  //是否关注了 
  const [cur, setcur] = useState(0) //默认页面初始值  
  const userIdRef = useRef(router.params.orgId || '');

  // const [orgAvar, setOrgAvar] = useState(router.params.orgAvar as string)

  // console.log('路径传过来的关注状态：', router.params.isFollowed)

  //切换页面事件
  const handleClick = (value) => {
    setcur(value)
  }

  //返回上一页
  const goBack = () => {
    Taro.navigateBack({
      delta: 1
    })
  }

  //查看更多直播动态
  const goLiveTrends = () => {
    Taro.navigateTo({
      url: `/subPages/my/orgLiveTrends/index?orgId=${userIdRef.current}`
    })
  }

  //查看我的关注
  const goOrgAttention = () => {
    Taro.navigateTo({
      url: '/subPages/my/orgAttention/index'
    })
  }

  //查看我的粉丝
  const goOrgFans = () => {
    Taro.navigateTo({
      url: '/subPages/my/orgFans/index'
    })
  }

  //是否点击了关注
  const isClickAttention = () => {
    setIsAttention(!isAttention)
    authFacade.addFollow(null as any, userIdRef.current, !isAttention)
  }

  const goToRoom = (roomId: string) => {
    Taro.navigateTo({
      url: `/pages/liveRoom/LiveDetails/index?roomId=${roomId}`
    })
  }

  // 开播提醒
  const reservation = (e, roomId: string) => {
    // 阻止事件冒泡
    e.stopPropagation()
    Taro.requestSubscribeMessage({
      tmplIds: [TMPID_READY, TMPID_NOW],
      success: (res) => {
        console.log('方法返回', res,);
        const newTmpIds = [] as Array<string>
        // 筛选得出accept的id
        for (const tmplId in res) {
          if (res[tmplId] === 'accept') {
            newTmpIds.push(tmplId)
          }
        }
        console.log('取到的新数组', newTmpIds);
        firstValueFrom(authFacade.submitsubMsgIds(CONFIG.APPID, roomId, newTmpIds));
        // 用户取消或者设置不接收信息时返回
        if (res[TMPID_READY] === 'reject' && res[TMPID_NOW] === 'reject') {
          Taro.showToast({
            title: '操作失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: (err) => {
        console.log('错误信息', err);
        if (err.errCode === 20004) {
          Taro.showToast({
            title: '用户关闭了消息通知，请在设置中打开',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }

  // 取得右上角胶囊高度，自定义标题与其对齐  
  useEffect(() => {
    Taro.getSystemInfo({
      success: function (res) {
        let myStatusBar = 0     // 状态栏高度
        let myCustomBar = 0  //导航栏高度
        let myNvaMartom = 0  //高度差
        let myNavHeight = 0   //胶囊高度
        let myNavWidth = 0   //胶囊宽度
        let myTopPadding = 0   //胶囊上边距 
        let myScreenWidth = 0  //屏幕宽度
        const custom = Taro.getMenuButtonBoundingClientRect();
        myStatusBar = res.statusBarHeight || 0;
        myNavHeight = custom.height
        myNavWidth = custom.width
        myTopPadding = custom.top
        myNvaMartom = custom.top - myStatusBar;
        myCustomBar = (myNvaMartom * 2 + custom.height)
        myScreenWidth = res.screenWidth
        setNavBarHeight(myCustomBar)
        setNavHeight(myNavHeight)
        setstatusBarHeight(myStatusBar)
        setTopMargin(myNvaMartom)
        setTopPadding(myTopPadding)
        setNavWidth(myNavWidth)
        setScreenWidth(myScreenWidth)
      }
    })
  }, [navBarHeight])

  useEffect(() => {
    //注册并执行所有rxjs流
    if (userIdRef.current === '') return
    const subscriptions: Subscription[] = [
      authFacade.getOrgDetails(userIdRef.current)
        .subscribe(
          (res: GetOrgDetailsRsp) => {
            setOrgDetails(res);
          }
        )
    ];
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  // 获取关注状态
  useEffect(() => {
    if (userIdRef.current === '' || userId === '') return
    authFacade.isFollowed(userId, userIdRef.current)
      .subscribe(
        (res) => {
          setIsAttention(res)
        }
      )
  }, [userId])

  useEffect(() => {
    //注册并执行所有rxjs流
    if (userIdRef.current === '') return
    const subscriptions: Subscription[] = [
      authFacade.getLatestShow(userIdRef.current, '')
        .subscribe(
          (res: AnchorlatestRsp[]) => {
            res.map(item => {
              if (item.status == 'started') {
                const data = item.rooms.slice(0, 1)
                setStartedList(data)
              } else if (item.status == 'notStarted') {
                const data = item.rooms.slice(0, 2)
                setNoStartedList(data)
              } else {
                const data = item.rooms.slice(0, 2)
                setEndedList(data)
              }
            })
            setLiveOrgList(res);
          }
        )
    ];
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  return (
    <View className='index' >
      <View className='top' >
        <View className='position' style={{ height: navBarHeight + 'px', width: (screenWidth - navWidth) + 'px', top: statusBarHeight + 'px' }}>
          <View className='navBox' style={{ height: navHeight + 'px', top: topMargin }}>
            <View className='orgName' >
              <Image className='goback' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png' onClick={goBack}></Image>
              <View className='name'>机构信息</View>
            </View>
          </View>
        </View>
      </View>
      <View className='main'>
        <View className='mainTop'>
          <View className='top-left'>
            <Image className='logo' src={orgDetails.orgLogo}></Image>
          </View>
          <View className='top-right'>
            <View className='box1'>
              <View className='fans' onClick={goOrgFans}>
                <View className='num'>{numFormat(orgDetails.following)}</View>
                <View className='text2'>粉丝</View>
              </View>
            </View>
            <View className='buttom' onClick={isClickAttention}>
              <Image src={isAttention ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/correct1.png' : 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/plus1.png'} className='plus_img'></Image>
              <View className='text'>{isAttention ? '已关注' : '关注'}</View>
            </View>
          </View>
        </View>
        <View className='box2'>
          <View className='title'>
            <View className='orgName'>{orgDetails.orgName}</View>
            <View className='ver'>认证机构</View>
          </View>
          <View className='introduce'>
            <Text>{orgDetails.desc}</Text>
          </View>
        </View>
        <View className='box3'>
          <View className='text3'>机构动态</View>
        </View>
        <ScrollView scrollY className='liveStaus'>
          {/* 直播中 */}
          {
            startedList && startedList.length > 0 && startedList.map((item, index) => (
              <View className='content1' key={index} onClick={() => goToRoom(item.roomId)}>
                <View className='left'>
                  <View className='leftImg'>
                    <Image src={item.picUrl} className='left_img'></Image>
                    <View className='status'>
                      <Text> 直播中</Text>
                    </View>
                    <View className='play'>
                      <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                    </View>
                  </View>
                  <View className='boxShadow'></View>
                </View>
                <View className='right'>
                  <View className='title'>
                    <Text>{item.roomName}</Text>
                  </View>
                  <View className='time'>
                    <Text>正在直播中</Text>
                  </View>
                </View>
              </View>
            ))
          }

          {/* 未开始直播 */}
          {
            noStartedList && noStartedList.length > 0 && (
              <View className='notStarted'>
                <View className='topTitle'>
                  <View className='Title'>未开始直播</View>
                  <View className='more' onClick={goLiveTrends}>查看更多</View>
                </View>
                {
                  noStartedList.map((item, index) => (
                    <View className='content2' key={index} onClick={() => goToRoom(item.roomId)}>
                      <View className='left'>
                        <View className='leftImg'>
                          <Image src={item.picUrl} className='left_img'></Image>
                          <View className='status'>
                            <Text> 待开始</Text>
                          </View>
                          <View className='play'>
                            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                          </View>
                        </View>
                        <View className='boxShadow'></View>
                      </View>
                      <View className='right'>
                        <View className='title'>
                          <Text>{item.roomName}</Text>
                        </View>
                        <View className='bottom'>
                          <View className='time'>开播时间：{formatTimes(new Date(item.startTime))}</View>
                          <View className='butn' onClick={(e) => reservation(e, item.roomId)}>开播提醒</View>
                        </View>
                      </View>
                    </View>
                  ))
                }
              </View>
            )
          }
          {/* 已结束直播 */}
          {
            endedList && endedList.length > 0 && (
              <View className='ended' >
                <View className='endedTitle'>
                  <View className='endState'>已结束直播</View>
                  <View className='endMore' onClick={goLiveTrends}>查看更多</View>
                </View>
                {
                  endedList.map((item, index) => (
                    <View className='content3' key={index} onClick={() => goToRoom(item.roomId)}>
                      <View className='endLeft'>
                        <View className='leftTu'>
                          <Image src={item.picUrl} className='left_img'></Image>
                          <View className='endstatus'>
                            <Text> 看回放</Text>
                          </View>
                          <View className='play'>
                            <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                          </View>
                        </View>
                        <View className='boxShadow1'></View>
                      </View>
                      <View className='right1'>
                        <View className='roomTitle'>
                          <Text>{item.roomName}</Text>
                        </View>
                        <View className='roomTime'>
                          <Text>结束时间：{formatTimes(new Date(item.endTime))}</Text>
                        </View>
                      </View>
                    </View>
                  ))
                }
              </View>
            )
          }
        </ScrollView>
      </View>
    </View>
  )
}
export default OrgInformation

